package com.llx.use.thread;


import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.llx.use.Threads;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : Linxu
 * @create : 2021/9/16
 * @update : 2023/2/20
 *            ^__^
 *            (**)\ _ __ _
 *            (__)\       )\/\
 *             U  ||------|
 *                ||     ||
 * ==============================
 * @desc   : 线程生命周期
 */
public class ThreadObserver implements DefaultLifecycleObserver {


    private static ConcurrentHashMap<LifecycleOwner, List<Runnable>> mTasks = new ConcurrentHashMap<>();

    public synchronized void subscribe(LifecycleOwner lifecycleOwner, Run runnable) {
        lifecycleOwner.getLifecycle().addObserver(this);
        if (!mTasks.containsKey(lifecycleOwner)) {
            List<Runnable> runnableList = Collections.synchronizedList(new ArrayList<Runnable>());
            runnableList.add(runnable);
            mTasks.put(lifecycleOwner, runnableList);
        } else {
            List<Runnable> runnableList = mTasks.get(lifecycleOwner);
            runnableList.add(runnable);
        }
    }

    public synchronized void unSubscribe(LifecycleOwner lifecycleOwner, Run runnable) {
        if (mTasks.containsKey(lifecycleOwner)) {
            List<Runnable> runnableList = mTasks.get(lifecycleOwner);
            runnableList.remove(runnable);
        }
    }

    @Override
    public synchronized void onDestroy(LifecycleOwner source) {
        List<Runnable> runnableList = mTasks.get(source);
        for (Runnable runnable : runnableList) {
            Threads.remove(runnable);
        }
        mTasks.remove(source);
    }

}
